<template>
  <div class="campusCircleWrap">
    <div class="sidebar">
      <van-sidebar v-model="activeKey">
        <div v-for="(item, index) in sidebarList" :key="index">
          <van-sidebar-item
            :title="item.modulename"
            v-if="+item.status === 1&+item.display===1"
            @click="changeSidebar(item)"
          />
        </div>
        <div class="more" @click="more"><van-icon name="plus" /></div>
      </van-sidebar>
    </div>
    <div class="content">
      <div
        class="postWrap"
        @click="toPostDetail(item)"
        v-for="(item, index) in postList"
        v-if="+item.display===1"
        :key="index"
      >
        <div class="postHeader">
          <div class="postHeader_img">
            <img
              v-if="item.user[0].headPic"
              :src="item.user[0].headPic.content"
              alt=""
              ref="headPic"
              :style="headPicHeight"
            />
            <img
              v-else
              src="static/images/headPic.png"
              alt=""
              ref="headPic"
              :style="headPicHeight"
            />
          </div>
          <span v-if="item.user[0]">{{ item.user[0].username }}</span>
        </div>
        <div class="postWord">
          <span class="postWord_span">{{ item.title }}</span>
          <p class="postWord_p">
            {{ item.content }}
          </p>
        </div>
        <div class="postImg">
          <img
            :src="pic.content"
            alt=""
            v-for="(pic, index) in item.pictures"
            :key="index"
          />
        </div>
        <div class="postFooter">
          <div class="read">
            <van-icon class="van-icon" name="browsing-history-o" />
            <span>{{ item.readNum }}</span>
          </div>
          <div class="comment">
            <van-icon name="comment-o" />
            <span>{{ item.commentList.length }}</span>
          </div>
          <div class="like" @click.stop="lickChange(item)">
            <van-icon
              v-if="item.likeList.indexOf(user[0]._id) === -1"
              name="like-o"
            />
            <van-icon v-else name="like" />
            <span>{{ item.likeList.length }}</span>
          </div>
        </div>
      </div>
      <van-empty
        description="还未有该模块的帖子"
        v-if="postList.length === 0"
      />
    </div>
    <van-popup
      v-if="isShowPopup"
      v-model="isShowPopup"
      class="addModel"
      :close-on-click-overlay="false"
      closeable
    >
      <div class="addModel_title">申请新的模块</div>
      <van-form @submit="onAddModelSubmit">
        <van-field
          v-model="modulename"
          name="申请模块名称"
          label="申请模块名称"
          placeholder="模块名称"
          maxlength="4"
          show-word-limit
          :rules="[{ required: true, message: '请填写申请模块名称' }]"
        />
        <van-field
          v-model="applyReason"
          rows="3"
          autosize
          type="textarea"
          maxlength="50"
          name="申请模块原因"
          label="申请模块原因"
          placeholder="申请模块原因"
          show-word-limit
          :rules="[{ required: true, message: '请填写申请模块原因' }]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
    </van-popup>
  </div>
</template>

<script>
import {
  createModule,
  getModule,
  getModulePost,
  getOneModule,
  getUser,
  setLikeList
} from '@/views/api/api.js'
import { Toast, Dialog } from 'vant'
export default {
  components: {},
  data () {
    return {
      activeKey: 0,
      isShowPopup: false,
      modulename: '',
      applyReason: '',
      user: '',
      sidebarList: [],
      postList: [],
      headPicHeight: '',
      isAdd: false // 是否点赞  不是取消赞
      // slidebarUser: []
    }
  },
  computed: {},
  created () {
    // console.log(window.WebSocket, 1111)
    this.init()
  },
  mounted () {},
  methods: {
    init () {
      // 获取用户信息
      this.user = JSON.parse(sessionStorage.getItem('user'))
      // 初始化，从数据库中获取所有的模块名称
      getModule().then((res) => {
        if (res.data.code) {
          // Toast.fail(res.data.msg)
        } else {
          this.sidebarList = res.data.Info
          let params = {
            modulename: this.sidebarList[0].modulename
          }
          // 获取某个模块的的postID
          getOneModule(params).then((res) => {
            if (res.data.code) {
              // Toast.fail(res.data.msg)
            } else {
              let params1 = {
                modulename: this.sidebarList[0].modulename,
                postID: res.data.Info[0].postID
              }
              // 查询第一个模块的所有帖子
              getModulePost(params1).then((res) => {
                if (res.data.code) {
                } else {
                  this.postList = res.data.Info
                  // this.slidebarUser = []
                  for (let i = 0; i < this.postList.length; i++) {
                    getUser(this.postList[i]._id).then((res) => {
                      if (!res.data.code) {
                      } else {
                      }
                    })
                  }
                }
              })
            }
          })
        }
      })
    },
    getHeadPicHeight () {
      // 头像的高度等于宽度
      let width = this.$refs.headPic.style.width
      this.headPicHeight.height = width + 'px'
    },
    lickChange (item) {
      // 判断当前用户是否点赞过，即是否在likeList中 在则从likeList删除，不在则push进去
      if (item.likeList.indexOf(this.user[0]._id) === -1) {
        this.isAdd = true
      } else {
        this.isAdd = false
      }
      // 将likeList写入数据库
      let params = {
        isAdd: this.isAdd,
        userID: this.user[0]._id,
        id: item._id
      }
      setLikeList(params).then((res) => {
        if (res.data.code) {
          // Toast.fail(res.data.msg)
        } else {
          item.likeList = res.data.Info[0].likeList
          // 轮询 WebSocket 2
          // var ws = new WebSocket('ws://localhost:8080')
          // ws.onopen = function () {
          //   ws.send('the request from client')
          // }
          // ws.onmessage = function (e) {
          //   console.log('from server: ' + e.data)
          // }
          // 修改成功
        }
      })
    },
    toPostDetail (item) {
      this.$router.push({
        name: 'postDetail',
        query: { postID: item._id }
      })
    },
    more () {
      this.modulename = ''
      this.applyReason = ''
      this.isShowPopup = true
    },
    // 点击新增模块提交按钮
    onAddModelSubmit () {
      this.user = JSON.parse(sessionStorage.getItem('user'))
      if (this.user[0]) {
        this.userID = this.user[0]._id
      }
      let params = {
        applyReason: this.applyReason,
        modulename: this.modulename,
        userID: this.userID
      }
      createModule(params).then((res) => {
        if (res.data.code) {
          Toast.fail(res.data.msg)
        } else {
          Dialog.alert({
            message: '申请成功，管理员审核通过后即可显示'
          }).then(() => {
            this.modulename = ''
            this.applyReason = ''
            this.isShowPopup = false
            this.init()
          })
        }
      })
    },
    changeSidebar (item) {
      let params = {
        modulename: item.modulename
      }
      getOneModule(params).then((res) => {
        if (res.data.code) {
          // Toast.fail(res.data.msg)
        } else {
          let params1 = {
            modulename: item.modulename,
            postID: res.data.Info[0].postID
          }
          getModulePost(params1).then((res) => {
            if (res.data.code) {
              // Toast.fail(res.data.msg)
            } else {
              this.postList = res.data.Info
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.van-sidebar-item--select::before {
  background-color: #1989fa;
}
.postFooter .van-icon-like::before {
  color: #ffb6c1;
}
.campusCircleWrap {
  height: calc(100vh - 50px - 46px);
  display: flex;
  justify-content: flex-start;
}
.van-sidebar {
  height: calc(100vh - 50px - 46px);
  overflow-y: auto;
}
.van-sidebar::-webkit-scrollbar {
  width: 0;
}
.content {
  background-color: #f7f8fa;
  overflow-y: auto;
  width: 100%;
}
.postHeader {
  text-align: left;
  display: flex;
  align-items: center;
}
.postHeader_img {
  width: 0.25rem;
  height: 0.25rem;
  margin-right: 0.08rem;
}
.postHeader_img > img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.postHeader > span {
  font-weight: 700;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.postWrap {
  margin: 5px 16px 5px 10px;
  padding: 5px;
  background-color: #ffffff;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}
.postImg {
  display: flex;
  flex-wrap: wrap;
}
.postImg .van-image {
  margin: 0.05rem;
}
.postImg img {
  margin: 0.05rem;
}
.postImg img {
  width: calc((100% - 50px) / 3);
}
.postWord {
  text-align: left;
  margin: 5px 0;
}
.postFooter {
  text-align: left;
  color: #9d9d9d;
  display: flex;
  justify-content: space-around;
}
.postFooter .van-icon {
  vertical-align: middle;
}
.postFooter > div {
  display: flex;
  align-items: center;
}
.postFooter > div > span {
  margin-left: 3px;
}
.more {
  height: 60px;
  line-height: 60px;
  background: #f7f8fa;
}
.addModel {
  width: 2.5rem;
  /* height: calc(100vh - 40%); */
}
.addModel_title {
  margin-top: 15px;
  font-weight: 700;
  font-size: 0.13rem;
}
.postWord_span {
  font-weight: 700;
  font-size: 0.12rem;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
}
.postWord_p {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
</style>
